package com.example.final_project.controller;

import com.example.final_project.entity.User;
import com.example.final_project.service.UserService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

@Tag(name = "用户管理", description = "用户相关的API接口")
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Operation(summary = "用户列表页面", description = "返回用户列表页面")
    @GetMapping("/list")
    public String list() {
        return "user/list";
    }

    @Operation(summary = "获取用户列表", description = "分页获取用户列表数据")
    @ApiResponse(responseCode = "200", description = "成功获取用户列表")
    @GetMapping("/api/list")
    @ResponseBody
    public Map<String, Object> apiList(
            @Parameter(description = "用户真实姓名") @RequestParam(required = false) String realName,
            @Parameter(description = "部门") @RequestParam(required = false) String department,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<User> pageInfo = userService.getList(realName, department, pageNum, pageSize);
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        return result;
    }

    @Operation(summary = "删除用户", description = "根据用户ID删除用户")
    @ApiResponse(responseCode = "200", description = "删除成功返回success，失败返回error")
    @PostMapping("/delete/{id}")
    @ResponseBody
    public String delete(@Parameter(description = "用户ID") @PathVariable Long id) {
        return userService.delete(id) ? "success" : "error";
    }

    @Operation(summary = "添加用户页面", description = "返回添加用户页面")
    @GetMapping("/add")
    public String add() {
        return "user/add";
    }

    @Operation(summary = "添加用户", description = "添加新用户，如果用户名已存在则返回username_exist")
    @ApiResponse(responseCode = "200", description = "添加成功返回success，失败返回error，用户名已存在返回username_exist")
    @PostMapping("/add")
    @ResponseBody
    public String addUser(@Parameter(description = "用户信息") @RequestBody User user) {
        if (userService.checkUsernameExist(user.getUsername())) {
            return "username_exist";
        }
        return userService.add(user) ? "success" : "error";
    }

    @Operation(summary = "编辑用户页面", description = "返回编辑用户页面")
    @GetMapping("/edit/{id}")
    public String edit(@Parameter(description = "用户ID") @PathVariable Long id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @Operation(summary = "更新用户", description = "更新用户信息")
    @ApiResponse(responseCode = "200", description = "更新成功返回success，失败返回error")
    @PostMapping("/edit")
    @ResponseBody
    public String edit(@Parameter(description = "用户信息") @RequestBody User user, HttpSession session) {
        User current = (User) session.getAttribute("user");
        boolean isSelf = current != null && current.getId().equals(user.getId());
        // 查询旧密码
        String oldPwd = current != null ? current.getPassword() : null;
        boolean updated = userService.update(user);
        if (updated && isSelf && oldPwd != null && !oldPwd.equals(user.getPassword())) {
            session.invalidate();
            return "reset";
        }
        return updated ? "success" : "error";
    }

    @Operation(summary = "用户登录", description = "根据用户名和密码登录")
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model, HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user); // 登录成功，存入session
            return "redirect:/main";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "user/login";
        }
    }

    @GetMapping("/login")
    public String loginPage(Model model, HttpServletRequest request) {
        Object registerSuccess = request.getSession().getAttribute("registerSuccess");
        if (registerSuccess != null) {
            model.addAttribute("registerSuccess", registerSuccess.toString());
            request.getSession().removeAttribute("registerSuccess");
        }
        return "user/login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/user/login";
    }

    @GetMapping("/changePassword")
    public String changePasswordPage() {
        return "user/change_password";
    }

    @PostMapping("/changePassword")
    @ResponseBody
    public String changePassword(HttpSession session, @RequestBody Map<String, String> params) {
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        User user = (User) session.getAttribute("user");
        if (user == null) return "未登录";
        if (!userService.login(user.getUsername(), oldPassword).getId().equals(user.getId())) {
            return "原密码错误";
        }
        user.setPassword(newPassword);
        userService.update(user);
        session.invalidate();
        return "success";
    }

    @GetMapping("/profile")
    public String profile(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        model.addAttribute("user", user);
        return "user/profile";
    }

    @GetMapping("/api/normalUsers")
    @ResponseBody
    public List<User> getNormalUsers() {
        // 只返回status!=1的普通用户
        List<User> all = userService.getList(null, null, 1, 1000).getList();
        List<User> normal = new java.util.ArrayList<>();
        for (User u : all) {
            if (u.getStatus() == null || u.getStatus() != 1) {
                normal.add(u);
            }
        }
        return normal;
    }

    @GetMapping("/register")
    public String registerPage() {
        return "user/register";
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String realName,
                           @RequestParam String department,
                           @RequestParam String phone,
                           Model model, HttpServletRequest request) {
        if (userService.checkUsernameExist(username)) {
            model.addAttribute("error", "用户名已存在");
            return "user/register";
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRealName(realName);
        user.setDepartment(department);
        user.setPhone(phone);
        user.setStatus(0); // 普通用户
        boolean success = userService.add(user);
        if (success) {
            // 注册成功，重定向到登录页并带上提示
            request.getSession().setAttribute("registerSuccess", "注册成功，请登录");
            return "redirect:/user/login";
        } else {
            model.addAttribute("error", "注册失败，请重试");
            return "user/register";
        }
    }
} 